package com.xuyuan.reflect.field;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.xuyuan.reflect.TestCommonClass;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.junit.jupiter.api.Test;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class Lang3FieldUtils {
    @Test
    public void test0() {
        Field[] allFields = FieldUtils.getAllFields(TestCommonClass.class);
        Arrays.stream(allFields).forEach(f -> System.out.println(f.getName()));

        List<Field> allFieldsList = FieldUtils.getAllFieldsList(TestCommonClass.class);
        allFieldsList.forEach(f -> System.out.println(f.getName()));

        Field field = FieldUtils.getDeclaredField(TestCommonClass.class, "name", false);
        if (Objects.nonNull(field)) System.out.println(field.getName());

        List<Field> fieldsListWithAnnotation = FieldUtils.getFieldsListWithAnnotation(TestCommonClass.class, JsonProperty.class);
        fieldsListWithAnnotation.forEach(f -> System.out.println(f.getName()));
    }

    @Test
    public void test1() throws NoSuchFieldException, IllegalAccessException {
        Field field = TestCommonClass.class.getDeclaredField("STATIC_FIELD");
        FieldUtils.removeFinalModifier(field, true);
        System.out.println(Modifier.toString(field.getModifiers()));
        TestCommonClass testCommonClass = new TestCommonClass();
        // 反射获取对象字段的value
        String str = (String) FieldUtils.readField(testCommonClass, "STATIC_FIELD", true);
        System.out.println(str);
        // 反射修改对象字段的value
        FieldUtils.writeField(testCommonClass, "STATIC_FIELD", "hello world", true);
        System.out.println((String) FieldUtils.readField(testCommonClass, "STATIC_FIELD", true));
    }

}
